package upc.component;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import upc.config.SmsConfig;


@Slf4j
@Component
public class SmsComponent {

    /**
     * 发送地址
     */
    private static final String URL_TEMPLATE = "https://zwp.market.alicloudapi.com/sms/sendv2mobile=%s&content=%s";

    private static final String CONTENT = "【智能云】您的验证码是%s。如非本人操作，请忽略本短信";

//    @Autowired
//    private RestTemplate restTemplate;

    @Autowired
    private SmsConfig smsConfig;

    @Autowired
    private RestTemplate restTemplate;

    /**
     * 发送短信验证码
     * @param to
     * @param
     */
    public void send(String to,String code){
//        String content = String.format(CONTENT,code);
//        String url = String.format(URL_TEMPLATE,to,content);
//
//        HttpHeaders headers = new HttpHeaders();
//        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
//        headers.set("Authorization","APPCODE "+smsConfig.getAppCode());
//        HttpEntity entity = new HttpEntity<>(headers);
//        ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.POST, entity, String.class);
//
//        if(response.getStatusCode().is2xxSuccessful()){
//            log.info("发送短信验证码成功");
//        }else {
//            log.error("发送短信验证码失败:{}",response.getBody());
//        }
        String host = "https://zwp.market.alicloudapi.com/sms/sendv2";
        String appcode = smsConfig.getAppCode();
        //最后在header中的格式(中间是英文空格)为Authorization:APPCODE 83359fd73fe94948385f570e3c139105
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", "APPCODE " + appcode);
        headers.set("Content-Type","application/x-www-form-urlencoded; charset=UTF-8");
        MultiValueMap<String, Object> map = new LinkedMultiValueMap<>();
        map.set("mobile", to);
        map.set("content", "【智能云】您的验证码是"+code+"。如非本人操作，请忽略本短信");
        HttpEntity<Object> http = new HttpEntity<>(map,headers);
        String result = restTemplate.postForObject(host,http,String.class);
        System.out.println(result);
    }


}
